package group

import (
	"api/pb/group"
	"api/pb/user"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetApplyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApplyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApplyListLogic {
	return &GetApplyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetApplyList 获取入群申请列表
func (l *GetApplyListLogic) GetApplyList(req *types.GroupApplyListRequest) (resp *types.GroupApplyListResponse, err error) {
	// 1. 获取申请列表
	applyList, err := l.svcCtx.GroupRPC.GetApplyList(l.ctx, &group.ApplyListRequest{GroupId: req.GroupID, Offset: req.Offset, Limit: req.Limit})
	if err != nil {
		return nil, err
	}

	// 2. 获取成员ID列表
	userIDList := make([]int64, 0)
	for _, item := range applyList.Data {
		userIDList = append(userIDList, item.UserId)
	}
	// 3. 获取成员信息
	userList, err := l.svcCtx.UserRPC.GetUserListByIDs(l.ctx, &user.UserListByIDsRequest{Ids: userIDList})
	if err != nil {
		return nil, err
	}

	// 4. 组装字典
	userInfoMap := make(map[int64]*user.UserInfo)
	for _, item := range userList.Data {
		userInfoMap[item.Id] = item
	}

	// 5. 转换为响应格式
	resp = &types.GroupApplyListResponse{
		Total: applyList.Total,
		Data:  make([]*types.GroupApplyInfo, 0),
	}
	for _, item := range applyList.Data {
		resp.Data = append(resp.Data, &types.GroupApplyInfo{
			UserID:     item.UserId,
			UserName:   userInfoMap[item.UserId].Name,
			Message:    item.Message,
			Status:     item.Status,
			CreateTime: item.CreateAt,
			UpdateTime: item.UpdateAt,
		})
	}
	return resp, nil
}
